import { connection } from '../app/database/mysql';
import { previewModel } from './preview.model';
import { getIdKitap, computeSet } from '../kitap/kitap.service';

/**
 * 获取内容
 */
export const getPreview = async (user_id: number, pageNo: number, pageSize: number) => {
  // 准备查询
  let statement = `
    SELECT *, COUNT(id) OVER () AS total FROM preview
  `;
  let where = []
  if (user_id >= 0) {
    where.push(`user_id = ` + user_id)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }

  statement += ` ORDER by id DESC limit ` + (pageNo > 0 ? (pageNo - 1) * pageSize : 0) + `,` + pageSize;
  
  // 执行查询
  const [data] = await connection.promise().query(statement);
  let totalCount: any;
  if (data[0] && data[0].total) totalCount = data[0].total;
  let totalPage = (totalCount % pageSize) > 0 ? parseInt(`${totalCount / pageSize}`) + 1 : totalCount / pageSize;


  for (let item of data as any) {
    item.kitap = await getIdKitap(item.book_id);

    let { multiset_count } = await computeSet(item.book_id)
    item.multiset_count = multiset_count;
  }

  // 提供数据
  let res = {
    data,
    totalPage,
    totalCount
  };
  
  return res;
}

/**
 * 创建内容
 */
export const createPreviews = async (post: previewModel) => {
  // 准备查询
  const statement = `
    INSERT INTO preview
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deletePreviews = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM preview
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId)

  // 提供数据
  return data;
}

/**
 * 添加收藏时查询
 */
export const reqGetPreviews = async (user_id: number, book_id: number) => {
  // 准备查询
  let statement = `
    SELECT * FROM preview
  `;
  let where = []
  if (user_id >= 0) {
    where.push(`user_id = ` + user_id)
  }

  if (book_id >= 0) {
    where.push(`book_id = ` + book_id)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data;
}
